<?php
/**
 *
 *
 */
namespace Yz\modules\Generic;

use Yz_Array;

abstract class Controller_AbstractFetch
    extends \Yz_Controller_Templated
{

    const ERROR_ITEM_NOT_FOUND = ':NotFound';

    /** The list of required arguments, parsed in order of appearance
     *      for each argument number N in list, call:
     *          set$name($arg[N])
     *      where $name is the argument's name
     *  @var array
     */
    protected $arguments = array();

    /** The default model's name
     *  @var string
     */
    protected $modelName = 'Default';

    /**
     *  @var Yz_Model_Interface
     */
    protected $model;


    /****************************
     *      Public methods      *
     ****************************/

    /** common `template method`
     *  @param Yz_Array
     *  @return this
     */
    public function doGet(Yz_Array $args)
    {
        return $this
            ->checkAccess()         // method of Yz_Controller_Templated
            ->parseArguments($args)
            ->fetchData()
            ->output()              // method of Yz_Controller_Templated
        ;
    }


    /******************************
     *     Protected methods      *
     ******************************/


    /** parse arguments
     *  @param Yz_Array args (from URI)
     *  @return this
     *  @throw Yz_Controller_Exception_InvalidArgument
     */
    protected function parseArguments(Yz_Array $args)
    {
        if ($this->arguments) {
            if ($args->count() < count($this->arguments)) {
                throw new \Yz_Controller_Exception_InvalidArgument("Invalid number of arguments");
            }
            foreach ($this->arguments as $i => $argName) {
                $method = 'set' . $argName;
                try {
                    $this->$method($args[$i]);
                } catch (\Yz_Exception_InvalidArgument $ex) {
                    throw new \Yz_Controller_Exception_InvalidArgument("Invalid argument value for {$argName}");
                }
            }
        }
        return $this;
    }


    /**
     *  @return this
     *
     */
    protected function selectModel()
    {
        debug();
        $model =& $this->model;
        if (null === $model) {
            $model = $this->module->selectModel($this->modelName);
        }
        return $model;
    }


    /**
     *  @return this
     *
     */
    protected function fetchData()
    {
        debug();
        // Example:
        // $model = $this->selectModel();
        // $this->_data = $model->fetch_data($this->_args);
        return $this;
    }


    /** get an i18n string for (abstract) error message
     *      defaults to :{Name}:Error , where {Name} is the controller's short name e.g. List
     *  @return string
     */
    protected function getErrorMessage()
    {
        return ':' . $this->name . ':Error';
    }

}